package reflect;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 自动实例化file包下的所有类
 */
public class Test04 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //获取类加载路径的根目录
        File dir = new File(
                Test04.class.getClassLoader().getResource("./file").toURI()
        );
        String path = dir.getAbsolutePath();
        System.out.println(path);

        File[] subs = dir.listFiles(
                f->!f.getName().contains("$")&&
                        f.getName().endsWith(".class")
        );
        for (File sub : subs){
            String fileName = sub.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            Class cls = Class.forName("file."+className);
//            Object obj = cls.newInstance();
//            System.out.println(obj);

            //自动调用该类的main方法
            Method method = cls.getMethod("main",String[].class);
            System.out.println("开始执行"+className+"main方法");
            method.invoke(null,(Object) new String[0]);

        }

    }
}
